package cn.org.gs.selector;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class SelectorDemo2 {

    // 客户端代码
    @Test
    public void clientDemo() throws Exception{
        // 1、获取通道，绑定主机和端口号
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

        // 2、切换到非阻塞模式
        socketChannel.configureBlocking(false);
        // 3、创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4、写入buffer数据
        buffer.put(new Date().toString().getBytes());
        // 5、模式切换
        buffer.flip();
        // 6、写入通道
        socketChannel.write(buffer);

        socketChannel.close();
    }

    // 服务端代码
    @Test
    public void serverDemo() throws Exception{

        // 1、获取服务端通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        // 2、切换非阻塞模式
        socketChannel.configureBlocking(false);
        // 3、创建buffer
        ByteBuffer serverByteBuffer = ByteBuffer.allocate(1024);
        // 4、绑定端口号
        socketChannel.bind(new InetSocketAddress(8080));
        // 5、获取selector选择器
        Selector selector = Selector.open();
        // 6、通道注册到channel，并且指出感兴趣的事件是Accept
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 7、选择器进行轮训，进行后续操作
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 遍历
            Iterator<SelectionKey> iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                // 获取就绪操作
                SelectionKey next = iterator.next();
                // 判断是什么操作
                if(next.isAcceptable()){
                    // 获取连接
                    SocketChannel accept = socketChannel.accept();
                    // 切换非阻塞模式
                    accept.configureBlocking(false);
                    // 注册
                    accept.register(selector, SelectionKey.OP_READ);
                } else if(next.isReadable()){
                    SocketChannel channel = (SocketChannel) next.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                    // 读取数据
                    int length = 0;
                    while ((length = channel.read(byteBuffer)) > 0){
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(), 0, length));
                        byteBuffer.clear();
                    }
                }
                iterator.remove();
            }
        }

    }
}
